package com.sc.oa.base;

import java.sql.SQLException;
import java.util.List;



import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;

@SuppressWarnings("unchecked")
public class BaseService<T>{
	
	protected HibernateTemplate ht;

	public HibernateTemplate getHt() {
		return ht;
	}

	public void setHt(HibernateTemplate ht) {
		this.ht = ht;
	}
	/**
	 * 
	 * @param hql
	 * @param values
	 * @return
	 */
	public int getCount(final String hql,final Object... values){

	return (int) ht.execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				int count=0;
				Query query=arg0.createQuery(hql);
				 setParams(query,values);
				count=Integer.parseInt(query.uniqueResult().toString());
				return count;
			}
		});
	}
	//分页查询
	public List<T> PageQuery(final String hql,final Pager p, final Object... values){
		return ht.executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session arg0)
					throws HibernateException, SQLException {
				Query query=arg0.createQuery(hql);
				query.setMaxResults(p.getPagesize());
				query.setFirstResult(p.getStartRow());
				setParams(query,values);
				return query.list();
			}
		});
	}
	

	public List<T> Query(final String hql){
		return ht.executeFind(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session arg0)
			throws HibernateException, SQLException {
			Query h=arg0.createQuery(hql);
			return h.list();
		}
		
	});
}
	//更新的操作 没有返回值
	public void updateObj(final String hql, final Object... values) {
	        ht.execute(new HibernateCallback(){
	            @Override
				public Object doInHibernate(Session session)
	            throws HibernateException, SQLException{
	                Query query=session.createQuery(hql);
	                setParams(query,values);
	                query.executeUpdate();
	                return null;    
	            }
	        });
	    }
	
	/*
	 * 执行sql语句
	 */
	public void makeTransientByIds(final String sql, final Object... values) {
        ht.execute(new HibernateCallback(){
            @Override
			public Object doInHibernate(Session session)
            throws HibernateException, SQLException{
                Query query=session.createQuery(sql);
                setParams(query,values);
                query.executeUpdate();
                return null;
            }
        });
    }
	//对多个参数的处理   对象之间的参数传递不需要返回值
	public void setParams(Query query, Object[] values) {
		if(values!=null&&values.length>0){
			for(int i=0;i<values.length;i++){
            query.setParameter( i, values[i]);
			}
		}
	}
}
